package thread;

import javax.sound.midi.SysexMessage;
import java.util.PriorityQueue;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 张杰
 * Date: 2022-04-12
 * Time: 17:05
 */
//创建一个类,表示一个任务.
class MyTask implements Comparable<MyTask>{
    //任务具体要干啥
    private Runnable runnable;
    //任务具体啥时候干,保证任务要执行的毫秒级时间戳
    private long time;

    //after是一个时间间隔,不是绝对的时间戳的值
    public MyTask(Runnable runnable,long after) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + after;
    }
    public void run() {
        runnable.run();
    }
    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTask o) {
        return (int) (this.time - o.time);
    }
}

class MyTimer {
    //定时器内部要能够存放多个任务
    private PriorityBlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();

    public void schedule(Runnable runnable,long delay) {
        MyTask task = new MyTask(runnable,delay);
        queue.put(task);
        //每次任务插入成功之后,都唤醒一下扫描程序,让线程重新检查一下队首的任务看是否时间到要执行
        synchronized (locker) {
            locker.notify();
        }
    }

    //用来记录当前时间和任务要执行的时间的时间差
    private  Object locker = new Object();
    public MyTimer() {
        Thread t = new Thread(() -> {
            while (true) {
                try {
                    MyTask task = queue.take();
                    long curTime = System.currentTimeMillis();
                    if(curTime < task.getTime()) {
                        //如果时间未到,就放回队列中
                        queue.put(task);
                        //制定一个等待时间
                        synchronized (locker) {
                            locker.wait(task.getTime() - curTime);
                        }
                    }else {
                        //如果时间到了就执行这个任务
                        task.run();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
}
public class Demo15 {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello timer!");
            }
        },3000);
        System.out.println("main");
    }
}
